<template>
  <div class="service-management">
    <div class="page-header">
      <h2>服务管理</h2>
      <el-button type="primary" @click="handleAdd">添加服务</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="服务名称">
          <el-input v-model="searchForm.name" placeholder="请输入服务名称" clearable />
        </el-form-item>
        <el-form-item label="服务类型">
          <el-select v-model="searchForm.category" placeholder="请选择服务类型" clearable>
            <el-option label="美容" value="美容" />
            <el-option label="寄养" value="寄养" />
            <el-option label="医疗" value="医疗" />
            <el-option label="训练" value="训练" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上线" :value="1" />
            <el-option label="下线" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 服务列表 -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="serviceList"
        border
        style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="服务名称" min-width="180" />
        <el-table-column prop="imageUrl" label="图片" width="100">
          <template slot-scope="scope">
            <el-image 
              style="width: 60px; height: 60px" 
              :src="scope.row.imageUrl ? getImageUrl(scope.row.imageUrl) : require('@/assets/default.jpg')"
              :preview-src-list="scope.row.imageUrl ? [getImageUrl(scope.row.imageUrl)] : []">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="服务类型" width="100">
          <template slot-scope="scope">
            <el-tag>{{ getServiceType(scope.row.category) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="100">
          <template slot-scope="scope">
            {{ scope.row.duration }}分钟
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="160">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-text="上线"
              inactive-text="下线"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
        />
      </div>
    </el-card>

    <!-- 服务表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form
        :model="serviceForm"
        :rules="rules"
        ref="serviceForm"
        label-width="100px"
      >
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name" />
        </el-form-item>
        <el-form-item label="服务类型" prop="category">
          <el-select v-model="serviceForm.category" placeholder="请选择服务类型">
            <el-option label="美容" value="美容" />
            <el-option label="寄养" value="寄养" />
            <el-option label="医疗" value="医疗" />
            <el-option label="训练" value="训练" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务价格" prop="price">
          <el-input-number
            v-model="serviceForm.price"
            :precision="2"
            :step="10"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="服务时长" prop="duration">
          <el-input-number
            v-model="serviceForm.duration"
            :min="0"
            :step="30"
          />
          <span class="unit">分钟</span>
        </el-form-item>
        <el-form-item label="图片上传" prop="imageUrl">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :http-request="handleFileUpload"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="serviceForm.imageUrl" :src="getImageUrl(serviceForm.imageUrl)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div v-if="serviceForm.imageUrl" class="image-actions">
            <el-button type="text" size="small" @click="previewImage">预览图片</el-button>
            <el-button type="text" size="small" @click="removeImage">删除图片</el-button>
          </div>
          <div class="image-tip">建议上传尺寸: 300x300px, 大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="服务描述" prop="description">
          <el-input
            type="textarea"
            v-model="serviceForm.description"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="注意事项" prop="notes">
          <el-input
            type="textarea"
            v-model="serviceForm.notes"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="serviceForm.status">
            <el-radio :label="1">上线</el-radio>
            <el-radio :label="0">下线</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getServiceList, createService, updateService, deleteService, updateServiceStatus } from '@/api/admin'
import { uploadFile } from '@/api/admin'
import { getToken } from '@/utils/auth'

export default {
  name: 'ServiceManagement',
  
  data() {
    return {
      loading: false,
      serviceList: [],
      searchForm: {
        name: '',
        category: '',
        status: ''
      },
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogType: 'add', // add or edit
      serviceForm: {
        name: '',
        category: '',
        price: 0,
        duration: 30,
        description: '',
        notes: '',
        imageUrl: '', // 图片URL
        status: 1
      },
      uploadUrl: '/api/files/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      rules: {
        name: [
          { required: true, message: '请输入服务名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择服务类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入服务价格', trigger: 'blur' }
        ],
        duration: [
          { required: true, message: '请输入服务时长', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入服务描述', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },

  computed: {
    dialogTitle() {
      return this.dialogType === 'add' ? '添加服务' : '编辑服务'
    }
  },

  created() {
    this.fetchData()
  },

  methods: {
    // 获取图片URL的方法
    getImageUrl(path) {
      // 如果路径为空，返回空字符串
      if (!path) return '';

      // 获取当前窗口的主机名和端口
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址

      // 如果已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }

      // 确保路径以/开头
      const normalizedPath = path.startsWith('/') ? path : '/' + path;

      // 返回完整URL
      return serverUrl + normalizedPath;
    },
    
    // 获取服务类型显示文本
    getServiceType(category) {
      return category || '未分类';
    },

    async fetchData() {
      this.loading = true
      try {
        const params = {
          pageNum: this.page.pageNum,
          pageSize: this.page.pageSize,
          ...this.searchForm
        }
        const { data } = await getServiceList(params)
        this.serviceList = data.list
        this.page.total = data.total
      } catch (error) {
        console.error('获取服务列表失败:', error)
        this.$message.error('获取服务列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.page.pageNum = 1
      this.fetchData()
    },

    resetSearch() {
      this.searchForm = {
        name: '',
        category: '',
        status: ''
      }
      this.handleSearch()
    },

    handleSizeChange(val) {
      this.page.pageSize = val
      this.fetchData()
    },

    handleCurrentChange(val) {
      this.page.pageNum = val
      this.fetchData()
    },

    handleAdd() {
      this.dialogType = 'add'
      this.serviceForm = {
        name: '',
        category: '',
        price: 0,
        duration: 30,
        description: '',
        notes: '',
        imageUrl: '',
        status: 1
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogType = 'edit'
      this.serviceForm = { ...row }
      this.dialogVisible = true
    },

    async handleStatusChange(row) {
      try {
        await updateServiceStatus(row.id, Number(row.status))
        this.$message.success('更新状态成功')
      } catch (error) {
        console.error('更新状态失败:', error)
        this.$message.error('更新状态失败')
        row.status = row.status === 1 ? 0 : 1 // 恢复状态
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该服务吗？', '提示', {
          type: 'warning'
        })
        await deleteService(row.id)
        this.$message.success('删除成功')
        this.fetchData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSubmit() {
      this.$refs.serviceForm.validate(async valid => {
        if (valid) {
          try {
            if (this.dialogType === 'add') {
              await createService(this.serviceForm)
              this.$message.success('添加服务成功')
            } else {
              await updateService(this.serviceForm.id, this.serviceForm)
              this.$message.success('更新服务成功')
            }
            this.dialogVisible = false
            this.fetchData()
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败')
          }
        }
      })
    },

    handleImageSuccess(response, file) {
      if (response.code === 200) {
        this.serviceForm.imageUrl = response.data;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.message || '图片上传失败');
      }
    },

    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    handleFileUpload(event) {
      const file = event.file;
      console.log('上传文件:', file.name, file.size);
      
      const formData = new FormData();
      formData.append('file', file);
      formData.append('directory', 'services');

      console.log('开始上传到服务器');
      uploadFile(formData, {
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log('上传响应:', response);
        if (response.code === 200) {
          this.serviceForm.imageUrl = response.data;
          this.$message.success('上传成功');
        } else {
          console.error('上传失败:', response.message);
          this.$message.error(response.message || '上传失败');
        }
      }).catch(error => {
        console.error('上传请求错误:', error);
        this.$message.error('上传失败: ' + (error.message || '未知错误'));
      });
    },
    
    previewImage() {
      if (!this.serviceForm.imageUrl) return;
      
      // 创建一个临时的大图预览
      const url = this.getImageUrl(this.serviceForm.imageUrl);
      const previewList = [url];
      
      // 使用Element UI的图片预览功能
      this.$image({
        urls: previewList,
        closeOnClickModal: true
      });
    },
    
    removeImage(event) {
      // 阻止事件冒泡，防止触发上传
      if (event) {
        event.stopPropagation();
      }
      
      // 清除图片相关数据
      this.serviceForm.imageUrl = '';
      
      this.$message.success('图片已删除');
      
      // 强制刷新视图
      this.$forceUpdate();
    }
  }
}
</script>

<style lang="scss" scoped>
.service-management {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .list-card {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  .unit {
    margin-left: 10px;
  }

  // 图片上传样式
  .image-uploader {
    .avatar {
      width: 148px;
      height: 148px;
      display: block;
      object-fit: cover;
      border-radius: 4px;
      border: 1px solid #eee;
    }
    
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      
      &:hover {
        border-color: #409EFF;
      }
    }
  }
  
  .image-actions {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }
  
  .image-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style> 